import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:pdf_render/pdf_render_widgets.dart';
import 'package:sp_util/sp_util.dart';

import '../../api/ApiUtils.dart';
import '../../api/request/LoginRegisterRequest.dart';
import '../../config/Constant.dart';
import '../../model/Bus.dart';
import '../../model/PDFFile.dart';
import '../../res.dart';
import '../../sqflite/CreateTableSqls.dart';
import '../../sqflite/DBUtil.dart';

import '../../utils/EventBus/EventBus.dart';
import '../../utils/color/ColorUtils.dart';
import '../../widgets/MyLocalImage.dart';
import '../../widgets/TextView.dart';
import '../dialog/SetDialog.dart';
import 'PDFView.dart';
import 'Selected.dart';
import 'package:date_format/date_format.dart';

class Allfile extends StatefulWidget {
  Allfile({Key? key, required this.star}) : super(key: key);
  bool star;

  @override
  State<Allfile> createState() => _AllfileState();
}

class _AllfileState extends State<Allfile> with AutomaticKeepAliveClientMixin {
  late List<PDFFile> list = [];
  late DBUtil dbUtil;
  StreamSubscription? subscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dbUtil = DBUtil();
    subscription = EventBusUtil.addListener<Bus>((event) async {
      if (event.label == Constant.ADD_FILE_MSG) {
        // print("ADD_FILE_MSG");
        File file = event.data as File;
        PDFFile pdfFile = PDFFile(
          name: file.path.split(Platform.pathSeparator).last,
          path: file.path,
          time: formatDate(
              DateTime.now(), [yyyy, "/", mm, "/", dd, "  ", HH, ":", nn]),
          size: formatFileSize(file.lengthSync()),
        );
        int id = await setData(pdfFile);
        pdfFile.id = id;
        list.insert(0, pdfFile);
        setState(() {});
      } else if (event.label == Constant.SORT_MSG) {
        getData(orderBy: getSort());
      } else if (event.label == Constant.STAR_MSG_Y ||
          event.label == Constant.STAR_MSG_N) {
        PDFFile file = event.data as PDFFile;
        update(file);
        getData(orderBy: getSort());
      } else if (event.label == Constant.DELETE_MSG) {
        //print("DELETE_MSG11111");
        PDFFile file = event.data as PDFFile;
        list.removeWhere((element) => file.id == element.id);
        delete(file);
        // getData(orderBy: getSort());
        setState(() {});
      } else if (event.label == Constant.CONVERT_EDIT_MSG) {
        PDFFile file = event.data as PDFFile;
        update(file);
        getData(orderBy: getSort());
      } else if (event.label == Constant.CONVERT_LOGIN_MSG) {
        login();
      }
    });
    getData(orderBy: getSort());
  }

  String getSort() {
    String? orderBy;
    switch (SpUtil.getInt(Constant.sort)) {
      case 0:
        orderBy = "id desc";
        break;
      case 1:
        orderBy = "id asc";
        break;
      case 2:
        orderBy = "name asc";
        break;
      case 3:
        orderBy = "name desc";
        break;
    }
    return orderBy!;
  }

  String formatFileSize(int size) {
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    double value = size.toDouble();
    int unitIndex = 0;
    while (value >= 1024 && unitIndex < units.length - 1) {
      value /= 1024;
      unitIndex++;
    }

    return '${(value * 100).round() / 100} ${units[unitIndex]}';
  }

  login() {
    apiShow(
      api: info(),
      success: (r) {},
    );
  }

  Future<int> setData(PDFFile pdfFile) async {
    await dbUtil.open();
    File pdf = File(pdfFile.path);
    Map<String, dynamic> paramters = <String, dynamic>{};
    paramters["name"] = pdfFile.name;
    paramters["path"] = pdfFile.path;
    paramters["star"] = false.toString();
    paramters["selects"] = false.toString();
    paramters["size"] = formatFileSize(pdf.lengthSync());
    paramters["time"] =
        formatDate(DateTime.now(), [yyyy, "/", mm, "/", dd, "  ", HH, ":", nn]);
    return await dbUtil.insertByHelper(file, paramters);
  }

  update(PDFFile pdfFile) async {
    await dbUtil!.open();
    Map<String, Object> paramters = <String, Object>{};

    bool star = !pdfFile.star;
    paramters["star"] = star.toString();
    paramters["name"] = pdfFile.name;
    await dbUtil?.updateByHelper(file, paramters, 'id=?', [pdfFile.id]);
  }

  delete(PDFFile pdfFile) async {
    await dbUtil!.open();
    await dbUtil
        ?.deleteByHelper(file, whereStr: 'id=?', whereArgs: [pdfFile.id]);
  }

  getData({String? orderBy}) async {
    list.clear();
    await dbUtil!.open();
    await dbUtil!.query(file, orderBy: orderBy).then((value) {
      for (Map<String, dynamic> map in value) {
        bool star = map["star"] == "false" ? false : true;
        if (widget.star && !star) {
          continue;
        }
        bool selects = map["selects"] == "false" ? false : true;
        list.add(PDFFile(
            id: map["id"] as int,
            name: map["name"],
            path: map["path"],
            time: map["time"],
            star: star,
            select: selects,
            size: map["size"]));
      }
      print(value);
      setState(() {});
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    EventBusUtil.removeListener(subscription!);
  }

  @override
  Widget build(BuildContext context) {
    return list.isEmpty
        ? Container(
            padding: const EdgeInsets.only(top: 100),
            child: Column(
              children: [
                const MyLocalImage(
                  Res.empty_img_home,
                  width: 100,
                  height: 100,
                ),
                TextView(
                  "please_upload".tr,
                  textAlign: TextAlign.center,
                  margin: const EdgeInsets.all(24),
                  maxLines: 2,
                  style: TextStyle(
                      color: rgba(150, 151, 153, 1),
                      fontSize: 16,
                      fontWeight: FontWeight.bold),
                )
              ],
            ),
          )
        : ListView.builder(
            itemBuilder: (c, index) {
              return GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  Get.to(PView(
                    pdfFile: list[index],
                  ));
                },
                onLongPress: () {
                  Get.to(const Selected(), arguments: list);
                },
                child: SizedBox(
                  height: 88,
                  child: Row(
                    children: [
                      Container(
                        margin: const EdgeInsets.only(right: 12),
                        width: 56,
                        height: 56,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(6),
                            border: Border.all(
                                color: rgba(230, 231, 235, 1), width: 0.5)),
                        alignment: Alignment.center,
                        child: PdfDocumentLoader.openFile(
                          list[index].path,
                          pageNumber: 1,
                        ),
                      ),
                      Expanded(
                        child: Column(
                          children: [
                            Expanded(
                              child: Row(
                                children: [
                                  Expanded(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        TextView(
                                              list[index].name,
                                          overflow: TextOverflow.clip,
                                          maxLines: 2,
                                          style: TextStyle(
                                              color: ColorUtils.text,
                                              fontSize: 14),
                                        ),
                                        Container(
                                          margin:
                                              const EdgeInsets.only(top: 10),
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              TextView(
                                                  "${list[index].time}   ${list[index].size}",
                                                  alignment: Alignment.center,
                                                  textAlign: TextAlign.center,
                                                  margin: const EdgeInsets.only(
                                                      right: 10),
                                                  style: TextStyle(
                                                      color: ColorUtils.text_,
                                                      fontSize: 10)),
                                              if (list[index].star)
                                                const MyLocalImage(
                                                  Res.sys_icon_file_star,
                                                  width: 12,
                                                  height: 12,
                                                )
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  MyLocalImage(
                                    Res.icon_file_more,
                                    width: 24,
                                    height: 24,
                                    margin: const EdgeInsets.all(6),
                                    onclick: () {
                                      Get.bottomSheet(SetDialog(
                                        pdfFile: list[index],
                                      ));
                                    },
                                  ),
                                ],
                              ),
                            ),
                            const Divider(
                              height: 1,
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
            itemCount: list.length,
          );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
